import axios from "axios";
import { Message } from "element-ui";
import store from "@/store";

const baseUrl = process.env.VUE_APP_BASE_API; // url接口地址

export { baseUrl };

const http = axios.create({
  timeout: 1000 * 20,
  baseURL: baseUrl
});
// 请求拦截
http.interceptors.request.use(
  config => {
    config.headers["Authorization"] = sessionStorage.getItem("token");
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截
http.interceptors.response.use(
  response => {
    const success = response.data.success; // 与后端约定的正确码 返回文件流有可能是undefined
    if (success !== false) {
      return Promise.resolve(response);
    } else {
      Message({ type: "error", message: response.data.msg });
      return Promise.reject(response);
    }
  },
  error => {
    if (error.message.includes("timeout")) {
      Message({ type: "error", message: "网络超时，请刷新重试" });
    } else if (error && error.response) {
      switch (error.response.status) {
        case 401:
          Message({ type: "error", message: "登录过期" });
          store.commit("common/TO_LOGIN");
          break;
        case 404:
          Message({ type: "error", message: "接口不存在" });
          break;
        case 500:
          Message({ type: "error", message: "服务器错误" });
          break;
      }
    } else {
      Message({ type: "error", message: error.message });
    }
    return Promise.reject(error);
  }
);

// 文件导出
function exportApi(method, url, data) {
  return new Promise((resolve, reject) => {
    const requestObj = {
      method,
      url,
      responseType: "blob"
    };
    method.toLowerCase() === "get"
      ? (requestObj.params = data)
      : (requestObj.data = data);
    http(requestObj)
      .then(res => {
        const elink = document.createElement("a");
        let download = res.headers["content-disposition"]
          .split(";")[1]
          .split("=")[1];
        download = decodeURI(download); // 解码
        elink.download = download;
        elink.href = URL.createObjectURL(res.data);
        elink.click();
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}

export { exportApi };
export default http;
